package petertel.pbx.utils;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;

public abstract class ConfigItem {

	private int lineno;
	private String line;
	private Flag flag;
	private List<ConfigItem> children = new ArrayList<ConfigItem>();

	public static enum Flag {
		insert, delete, update
	}

	public int getLineno() {
		return lineno;
	}

	public void getAll(List<ConfigItem> all) {
		all.add(this);
		for (ConfigItem child : children) {
			child.getAll(all);
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		Formatter formatter = new Formatter();
		sb.append(formatter.format("%04d %s\n", lineno, lineno > 0 ? line : ""));
		formatter.close();
		//
		if (children != null)
			for (ConfigItem citem : children) {
				sb.append(citem);
			}
		return sb.toString();
	}

	public void addChild(ConfigItem citem) {
		children.add(citem);
	}

	public Iterator<ConfigItem> getChildren() {
		return children.iterator();
	}

	protected void setLineno(int lineno) {
		this.lineno = lineno + 1;
	}

	public String getLine() {
		return line;
	}

	public void setLine(String line) {
		this.line = line;
	}

	public Flag getFlag() {
		return flag;
	}

	public void setFlag(Flag flag) {
		this.flag = flag;
	}

	public void remove() {
		flag = Flag.delete;
		Iterator<ConfigItem> iter = children.iterator();
		while (iter.hasNext()) {
			ConfigItem child = iter.next();
			if (child.getFlag() == Flag.insert) {
				iter.remove();
			} else {
				child.remove();
			}
		}
	}

}
